<template>
  <div class="role_box">
    <el-table style="width: 100%" stripe :data="tableData">
      <el-table-column label="序号" type="index" :index="tableIndex">
      </el-table-column>
      <el-table-column
        label="用户名"
        prop="user.username"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column label="头像" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-image
            :src="scope.row.user.avatar"
            class="avatar"
            :preview-src-list="[scope.row.user.avatar]"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="角色" show-overflow-tooltip>
        <template slot-scope="scope">
          <div v-for="item in scope.row.roleList" :key="item.id">
            {{ item.name }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" show-overflow-tooltip>
        <template slot-scope="scope">
          <div v-if="isSuperAdmin(scope.row.roleList)">
            超级管理员不可被编辑
          </div>
          <div v-else-if="scope.row.user.status == 1">未审核的新用户</div>
          <div v-else>
            <el-button type="primary" @click="openDialog(scope.row)"
              >编辑角色</el-button
            >
            <el-button
              type="danger"
              @click="stopOrStart(scope.row.user, 0)"
              v-if="scope.row.user.status == 2"
              >停用</el-button
            >
            <el-button
              type="danger"
              @click="stopOrStart(scope.row.user, 2)"
              v-else-if="scope.row.user.status == 0"
              >启用</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页插件 -->
    <el-pagination
      layout="prev, pager, next"
      background
      hide-on-single-page
      class="pagination"
      :page-size="size"
      :current-page="current"
      :total="total"
      @prev-click="getTableData"
      @next-click="getTableData"
      @current-change="getTableData"
    >
    </el-pagination>
    <el-dialog
      title="角色管理"
      :visible.sync="roleDialog"
      width="45%"
      class="dialog_box"
    >
      <el-transfer
        :titles="['全部角色', '已有角色']"
        class="transfer_bofy"
        :data="allRole"
        v-model="hasRole"
      ></el-transfer>
      <div class="transfer_button">
        <el-button type="primary" @click="changeRole">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Loading } from "element-ui";
import axios from "@/request";

export default {
  name: "Role",
  data() {
    return {
      tableData: [],
      current: 1,
      size: 5,
      total: 100,
      roleDialog: false,
      userId: null,
      allRole: [],
      hasRole: [],
    };
  },
  mounted() {
    this.getTableData(1);
  },
  methods: {
    tableIndex(index) {
      return (this.current - 1) * this.size + index + 1;
    },
    getTableData(current) {
      let loading = Loading.service({
        text: "正在加载...",
        target: ".role_box",
      });
      axios
        .get("/auth/getAllUserAndRoleButSuperAdmin", {
          params: {
            current: current,
            size: this.size,
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.total = res.data.data.total;
            this.tableData = res.data.data.records;
          } else {
            this.$message.error(res.data.data);
          }
          loading.close();
        })
        .catch((e) => {});
    },
    isSuperAdmin(roleList) {
      for (const element of roleList) {
        if (element.name == "superadmin") return true;
      }
      return false;
    },
    stopOrStart(user, status) {
      let loading = Loading.service({
        text: "正在加载...",
        target: ".role_box",
      });
      axios
        .post("/auth/changeStatus", {
          user: user,
          status: status,
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.$message.success("修改成功");
            user.status = status;
          } else {
            this.$message.error("修改失败");
          }
          loading.close();
        })
        .catch((e) => {
          loading.close();
        });
    },
    getAllRole() {
      return new Promise((resolve, reject) => {
        axios
          .get("/role/getAllRole")
          .then((res) => {
            if (res.data.code == 200) {
              this.allRole = [];
              res.data.data.forEach((element) => {
                if (element.name == "user" || element.name == "superadmin") {
                  this.allRole.push({
                    key: element.id,
                    label: element.name,
                    disabled: true,
                  });
                } else {
                  this.allRole.push({ key: element.id, label: element.name });
                }
              });
            }
            resolve();
          })
          .catch((e) => {
            reject();
          });
      });
    },
    async openDialog(row) {
      this.userId = row.user.id;
      await this.getAllRole();
      this.hasRole = [];
      for (const element of row.roleList) {
        if (element.deleted == 0) {
          this.hasRole.push(element.id);
        }
      }
      this.roleDialog = true;
    },
    changeRole() {
      let loading = Loading.service({
        text: "正在加载...",
        target: ".dialog_box",
      });
      axios
        .post("/role/changeUserRole", {
          userId: this.userId,
          roleList: this.hasRole,
        })
        .then((res) => {
          loading.close();
          this.roleDialog = false;
          if (res.data.code == 200) {
            this.$message.success("修改成功!");
            this.getTableData(this.current);
          } else {
            this.$message.error("修改失败!");
          }
        })
        .catch((e) => {
          loading.close();
          this.roleDialog = false;
        });
    },
  },
};
</script>

<style scoped>
.avatar >>> .el-image__inner {
  max-height: 100px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.transfer_bofy {
  display: flex;
  justify-content: center;
  align-items: center;
}

.transfer_button {
  display: flex;
  justify-content: right;
  padding: 30px 0 0;
}
</style>